<script setup>
import { ref, reactive, toRaw } from 'vue'
import { ElMessage } from 'element-plus'

//引入API
// import {} from '../../api/dept.js'

function createFormData() {//表单数据对象模板
    return {name:'',addr:''};
}
//表单数据
const formData = ref(createFormData());
const formRef = ref(null);//表单组件
const formRules = reactive({//校验规则
    name: [{required:true, validator: (rule, value, callback)=>{
        if(!value) {
            callback(new Error('请填写部门名称'));
            return;
        }
        if(value.length > 20) {
            callback(new Error('部门名称长度范围是1~20'));
            return;
        }
        //TODO: 发送请求,校验是否重复
        setTimeout(()=>{//模拟
            if(Math.random() > 0.7) {
                callback();//成功
            } else {
                callback(new Error('该部门名称已存在'));//失败
            }
        }, 500);
    }, trigger:'blur'}],
    addr: [
        {required:true, message:'请填写所在位置', trigger:'blur'},
        {min:1, max:10, message:'内容长度是1~100', trigger:'blur'},
    ]
});
function doFormSubmit() {//表单校验与提交
    formRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('校验通过');
            //TODO: 提交添加的数据
            let params = toRaw(formData.value);
            console.log('submit:', params);

            //成功后执行以下操作
            ElMessage.success('添加成功');
        } else { 
            //console.log('校验不通过:', fields);
            ElMessage.warning('信息有误，请查看对应的提示信息');
        }
    });;
}
function doFormReset() {//表单重置
    formRef.value.resetFields();
}

</script>
<template>
    <div class="dept-add-page-dl" >
        <div class="title-dl" >部门添加</div>
        <el-form :model="formData" label-width="130px" :rules="formRules" 
        status-icon ref="formRef">
            <el-form-item label="部门名称：" prop="name">
                <el-input v-model="formData.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="部门位置：" prop="addr">
                <el-input type="textarea" v-model="formData.addr" autocomplete="off" autosize />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="doFormSubmit">确定</el-button>
                <el-button @click="doFormReset" >重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<style scoped>
.dept-add-page-dl {
    width: 800px;
}
.title-dl {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
}
</style>